package com.midian.controller.sys;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.midian.common.exception.BizException;
import com.midian.common.filter.annotation.Validate;
import com.midian.common.system.RetManager;
import com.midian.common.utils.JuHeSendSMSUtils;
import com.midian.common.utils.StringUtil;
import com.midian.model.sys.ValidateCode;
import com.midian.service.sys.IValidateCodeService;
import com.midian.service.user.IUserService;

import net.sf.json.JSONObject;

/**
 * 验证码控制器
 * 
 * @author jiangjing
 * 
 */
@Controller("validateCodeController")
public class ValidateCodeController {
	/** Log4j日志对象 */
	private static final Logger LOG = Logger.getLogger(ValidateCodeController.class);

	/** 验证码业务 */
	private IValidateCodeService validateCodeService;

	/** 用户业务 */
	private IUserService userService;

	@Resource(name = "userService")
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	@Resource(name = "validateCodeService")
	public void setValidateCodeService(IValidateCodeService validateCodeService) {
		this.validateCodeService = validateCodeService;
	}

	/**
	 * 发送验证码
	 * 
	 * @param client_key
	 * @param phone
	 *            手机号码
	 * @param type
	 *            验证码类型(1：注册/修改新手机号,2：忘记密码,3：修改手机号)
	 * @return
	 */
	@Validate(retCode = RetManager.common_send_error)
	@RequestMapping(value = "/send_code", method = RequestMethod.GET)
	public @ResponseBody
	Object sendCode(String client_key, String phone, String type) throws Exception {
		JSONObject json = new JSONObject();
		try {
			if (IValidateCodeService.CODE_REGIST.equals(type)||IValidateCodeService.UPDATE_PHONE.equals(type)) {// 注册
				// 检测手机号是否被注册
				if (this.userService.isExistUserByAccount(phone)) {
					RetManager.getInstance().setRetError(json, RetManager.common_phone_registered);
					return json;
				}
			}

			// 忘记密码时,先验证接收短信手机是否已注册为帐号
			if (IValidateCodeService.CODE_FORGETPW.equals(type)) {
				// 检测手机号
				if (!this.userService.isExistUserByAccount(phone)) {
					RetManager.getInstance().setRetError(json, RetManager.common_phone_not_exist);
					return json;
				}
			}

			ValidateCode validateCode = new ValidateCode();
			// 随机数
			String code = StringUtil.getRandomNumString(4);
			String tplId = ""; // 短信模板id
			if ("1".equals(type)) {
				tplId = JuHeSendSMSUtils.TPL_ID_REGISTER; // 注册
			} else if ("2".equals(type)) {
				tplId = JuHeSendSMSUtils.TPL_ID_FORGET_PWD; // 忘记密码
			} else {
				tplId = JuHeSendSMSUtils.TPL_ID_GET_CODE; // 修改手机号
			}
			if (!JuHeSendSMSUtils.sendSMS(phone, code, tplId)) {
				throw new BizException("发送验证码出错！");
			}
			validateCode.setCode(code); // 验证码
			validateCode.setPhone(phone); // 电话
			this.validateCodeService.add(validateCode);
		} catch (BizException e) {
			LOG.error(e.getMessage());
			throw e;
		}
		RetManager.getInstance().setRetSuccess(json, RetManager.common_send_success);
		return json;
	}

	/**
	 * 验证验证码
	 * 
	 * @param client_key
	 * @param phone
	 * @param type
	 * @param invite_code
	 * @param code
	 * @return
	 */
	@Validate(retCode = RetManager.common_validate_error)
	@RequestMapping(value = "/validate_code", method = RequestMethod.GET)
	public @ResponseBody
	Object validateCode(String client_key, String phone, String code) throws BizException {
		JSONObject json = new JSONObject();
		try {
			if (!this.validateCodeService.isExistCode(phone, code)) {
				RetManager.getInstance().setRetError(json, RetManager.common_verification_code_error);
				return json;
			}
		} catch (BizException e) {
			LOG.error(e.getMessage());
			throw e;
		}
		RetManager.getInstance().setRetSuccess(json, RetManager.common_validate_success);
		return json;
	}
}
